package com.igroupes.ovineherd.model.attribute.file;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.igroupes.ovineherd.dto.response.Meta;
import com.igroupes.ovineherd.entity.DataModelAttributeEntity;
import com.igroupes.ovineherd.enums.BooleanKey;
import com.igroupes.ovineherd.exception.ModelException;
import com.igroupes.ovineherd.model.IParentModelData;
import com.igroupes.ovineherd.model.Style.*;
import com.igroupes.ovineherd.model.attribute.BasicAttribute;
import com.igroupes.ovineherd.model.dto.FieldApiResponse;
import com.igroupes.ovineherd.model.enums.MySqlTypeKey;
import com.igroupes.ovineherd.model.utils.ListUtils;
import com.igroupes.ovineherd.query.FieldQuery;
import com.igroupes.ovineherd.query.ModelDataJsonAttributeQuery;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件基础类
 */
@EqualsAndHashCode(callSuper = true)
@Data
@ToString(callSuper = true)
public class FileBasicAttribute extends BasicAttribute {

    public static final String SIZE_LABEL = "最大个数";
    public static final Integer MAX_NUMBER = 10;
    public static final Integer MIN_NUMBER = 1;


    public static final String CHECKSUFFIX_LABEL = "允许文件格式";
    public static final String SUFFIX_LABEL = "其它格式";
    public static final String SUFFIX_DESC = "其余文件格式";

    protected NumberStyle size;
    protected CheckboxStyle checkSuffix;
    protected EnumStyle suffix;

    protected FileBasicAttribute() {
        super();
        this.size = new NumberStyle(SIZE_LABEL, MIN_NUMBER, true,MIN_NUMBER, MAX_NUMBER);
        this.checkSuffix = new CheckboxStyle(CHECKSUFFIX_LABEL,"", this.getGroups());
        this.suffix = new EnumStyle(SUFFIX_LABEL, this.getSuffixEnum(),SUFFIX_DESC);
    }
    private JSONObject getSuffixEnum() {
//        List<TextStyle> list = new ArrayList();
        return new JSONObject(new TextStyle("描述", "", true, "填写文件后缀",20, ""));
    }
    private List<Group> getGroups() {
        List<Group> groups = new ArrayList<>();
        groups.add(new Group("jpeg",".jpeg"));
        groups.add(new Group("png",".png"));
        groups.add(new Group("gif",".gif"));
        groups.add(new Group("svg",".svg"));

        groups.add(new Group("mpeg",".mpeg"));
        groups.add(new Group("avi",".avi"));
        groups.add(new Group("rm",".rm"));
        groups.add(new Group("mp4",".mp4"));
        groups.add(new Group("flv",".flv"));

        groups.add(new Group("mp3",".mp3"));
        groups.add(new Group("wma",".wma"));

        groups.add(new Group("word",".word"));
        groups.add(new Group("pdf",".pdf"));
        groups.add(new Group("zip",".zip"));
        groups.add(new Group("rar",".rar"));

        groups.add(new Group("txt",".txt"));
        groups.add(new Group("doc",".doc"));
        groups.add(new Group("docx",".docx"));
        groups.add(new Group("ppt",".ppt"));
        groups.add(new Group("pptx",".pptx"));
        groups.add(new Group("xls",".xls"));
        groups.add(new Group("xlsx",".xlsx"));

        return groups;
    }
    public Boolean verifyField(FileBasicAttribute fileBasicAttribute) {
        super.verifyField(fileBasicAttribute);
        new NumberStyle().verify(fileBasicAttribute.getSize());
        new CheckboxStyle().verify(fileBasicAttribute.getCheckSuffix());
        new EnumStyle().verify(fileBasicAttribute.getSuffix());
        return true;
    }
    public Boolean verifyFieldV2(FileBasicAttribute basic) {
        super.verifyFieldV2(basic);
        new NumberStyle().verify(new NumberStyle(SIZE_LABEL, basic.getSize().getValue(), true,MIN_NUMBER, MAX_NUMBER));
        new CheckboxStyle().verify(new CheckboxStyle(CHECKSUFFIX_LABEL,basic.getCheckSuffix().getValue(), this.getGroups()));
        new EnumStyle().verify(new EnumStyle(SUFFIX_LABEL, basic.getSuffix().getItems(),SUFFIX_DESC));
        return true;
    }
    @Override
    public List<FieldQuery> sqlField(IParentModelData parentModelData, DataModelAttributeEntity dataModelAttributeEntityOld) {
        List<FieldQuery> fieldQueries = super.sqlField(parentModelData,dataModelAttributeEntityOld);
        FieldQuery fieldQuery = fieldQueries.get(0);
        FileBasicAttribute fileBasicAttribute = (FileBasicAttribute) parentModelData.getAttributes();
        if(Convert.toInt(fileBasicAttribute.getSize().getValue()) > 10){
            fieldQuery.setType(MySqlTypeKey.TEXT.getCode());
        }else {
            fieldQuery.setType(MySqlTypeKey.VARCHAR.getCode());
        }
        fieldQuery.setLength(Convert.toInt(fileBasicAttribute.getSize().getValue()) * 150);

        DataModelAttributeEntity dataModelAttributeEntity = fieldQuery.getDataModelAttributeEntity();
        JSONObject jsonObject = dataModelAttributeEntity.getJson();
        jsonObject.set("checkSuffix", Convert.toStr(fileBasicAttribute.getCheckSuffix().getValue()));
        jsonObject.set("suffix", ListUtils.toListString((fileBasicAttribute.getSuffix().getValue())));
        jsonObject.set("size", Convert.toInt(fileBasicAttribute.getSize().getValue()));
        dataModelAttributeEntity.setJson(jsonObject);
        fieldQuery.setDataModelAttributeEntity(dataModelAttributeEntity);
        fieldQueries.set(0,fieldQuery);
        return fieldQueries;
    }
    @Override
    public JSONObject getAttribute(ModelDataJsonAttributeQuery modelDataJsonAttributeQuery) {
        JSONObject jsonObject = super.getAttribute(modelDataJsonAttributeQuery);
        jsonObject.set("size", new NumberStyle(SIZE_LABEL, modelDataJsonAttributeQuery.getJson().get("size"), true,MIN_NUMBER, MAX_NUMBER) );
        jsonObject.set("checkSuffix", new CheckboxStyle(CHECKSUFFIX_LABEL,modelDataJsonAttributeQuery.getJson().get("checkSuffix"),  getGroups()));
        if(ObjectUtil.isNotNull(modelDataJsonAttributeQuery.getJson().get("suffix"))){
            jsonObject.set("suffix",new EnumStyle(SUFFIX_LABEL, ListUtils.parseString(modelDataJsonAttributeQuery.getJson().get("suffix").toString()),this.getSuffixEnum(),SUFFIX_DESC));
        }
        return jsonObject;
    }
    @Override
    public List<FieldApiResponse> verifyRequestData(DataModelAttributeEntity modelAttributeEntity, Object value) {
        super.verifyRequestData(modelAttributeEntity, value);
        List<FieldApiResponse> fieldApiResponses = new ArrayList<>();
        if(value == null){
            return fieldApiResponses;
        }
        JSONObject jsonObject = modelAttributeEntity.getJson();
//        List<String> checkSuffix = ListUtils.parseString(jsonObject.get("checkSuffix").toString());
//        List<String> suffix = ListUtils.parseString(jsonObject.get("suffix").toString());
        Integer size = Convert.toInt(jsonObject.get("size"), 1);
        FieldApiResponse fieldApiResponse = new FieldApiResponse();
        fieldApiResponse.setDbName(modelAttributeEntity.getDbName());
        fieldApiResponse.setIsStr(true);
        fieldApiResponse.setType(MySqlTypeKey.TEXT.getCode());
        fieldApiResponses.add(fieldApiResponse);
        if(size == 1){
            if(modelAttributeEntity.getIsNull().equals(BooleanKey.FALSE.getCode())){
                if(ObjectUtil.isNull(value)){
                    throw new ModelException(String.format("%s值不能为空,请检测格式是否正确",modelAttributeEntity.getName()));
                }
            }
            String url = Convert.toStr(value);
//            if(!checkSuffix.contains(url) && !suffix.contains(url)){
//                throw new ModelException(String.format("%s值错误，请确认取值",modelAttributeEntity.getName()));
//            }
            fieldApiResponse.setValue(url);
        }else{
            List<String> list = null;
            try {
                 list  = ListUtils.parseString(Convert.toStr(value));
            }catch (Exception ex){
                // -----如果转换出现问题，就看作字符串类型-----
                if(modelAttributeEntity.getIsNull().equals(BooleanKey.FALSE.getCode())){
                    if(ObjectUtil.isNull(value)){
                        throw new ModelException(String.format("%s值不能为空,请检测格式是否正确",modelAttributeEntity.getName()));
                    }
                }
                String url = Convert.toStr(value);
                fieldApiResponse.setValue(url);
                return fieldApiResponses;
            }

            if(modelAttributeEntity.getIsNull().equals(BooleanKey.FALSE.getCode())){
                if(list.size() == 0){
                    throw new ModelException(String.format("%s值不能为空,请检测格式是否正确",modelAttributeEntity.getName()));
                }
            }

            if(list.size() > size){
                throw new ModelException(String.format("%s数据集合最大不能超过%s",modelAttributeEntity.getName(),size));
            }
//            for (String st: list){
//                if(!checkSuffix.contains(st) && !suffix.contains(st)){
//                    throw new ModelException(String.format("%s值错误，请确认取值",modelAttributeEntity.getName()));
//                }
//            }
            fieldApiResponse.setValue(ListUtils.toJsonString(list));
        }


        return fieldApiResponses;
    }

    @Override
    public Meta getMeta(ModelDataJsonAttributeQuery dataModelAttributeEntity){
        return null;
    }

    @Override
    public Object getData(DataModelAttributeEntity modelAttributeEntity, Object value) {
        JSONObject jsonObject = modelAttributeEntity.getJson();
        Integer size = Convert.toInt(jsonObject.get("size"), 1);
        if(size == 1){
            return value;
        }
        if(ObjectUtil.isBasicType(value)){
            return ListUtils.parseString(value.toString());
        }
        return value;
    }
}